//
//  FindMusicCollectionLayout.swift
//  Pods
//
//  Created by eme on 2017/4/12.
//
//

let _naviHeight : CGFloat = 0
// 需要保持悬浮的sectionIndex
let pinSectionIndex = 0

class FindMusicCollectionLayout: UICollectionViewFlowLayout, UICollectionViewDelegateFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 获取父类返回的所有item的layout信息
        
        var superArray = NSArray(array: super.layoutAttributesForElements(in: rect)!, copyItems: true) as! [UICollectionViewLayoutAttributes]
        
        let indexPath = IndexPath(item: 0, section: pinSectionIndex)
        // 获取当前section在正常情况下已经离开屏幕的header的信息
        let attributes = self.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath)
        
        if let attributes = attributes {
            superArray.append(attributes)
        }
        
        // 遍历superArray的sectionHeader信息，使它可以在当前section还没完全离开屏幕的时候一直显示
        for attributes in superArray {
            
            if attributes.representedElementKind == UICollectionElementKindSectionHeader && attributes.indexPath.section == pinSectionIndex {
                // 得到当前header所在分区的cell的数量
                let numberOfItemsInSection = self.collectionView!.numberOfItems(inSection: attributes.indexPath.section)
                // 得到第一个item的indexPath
                let firstItemIndexPath = IndexPath(item: 0, section: attributes.indexPath.section)
                var firstItemAttributes : UICollectionViewLayoutAttributes!
                
                if numberOfItemsInSection > 0 {
                    firstItemAttributes = self.layoutAttributesForItem(at: firstItemIndexPath)
                } else {
                    firstItemAttributes = UICollectionViewLayoutAttributes()
                    let y = attributes.frame.maxY + self.sectionInset.top
                    firstItemAttributes.frame = CGRect(x: 0, y: y, width: 0, height: 0)
                }
                
//                var rect = attributes.frame
                
                let offset = self.collectionView!.contentOffset.y + _naviHeight
                
                let headerY = firstItemAttributes.frame.origin.y - rect.height - self.sectionInset.top
                // 设置section的Y值，确保section悬浮在屏幕上方
                let maxY = max(offset, headerY)
                
                let frame = CGRect(x: rect.origin.x, y: maxY, width: rect.size.width, height: rect.size.height)
            
//                rect.maxY = maxY
                
                attributes.frame = frame
                // 这里的zIndex需要大于10，不然会被别的attributes覆盖掉
                attributes.zIndex = 20
            }
        }
        return superArray
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
